package com.hs.libs;

import com.hs.utils.Tools;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.util.List;

public class BaseUITasks {
    static long maxWait = 30; //seconds
    private static Logger logger = Logger.getLogger(BaseUITasks.class);

    protected static WebElement findElementByXpath(String objXpath, WebDriver driver) throws Exception {
        WebElement wele = null;
        long start = System.currentTimeMillis();
        long now = System.currentTimeMillis();
        while (((now - start) < maxWait * 1000) && (wele == null)) {
            Tools.wait(1);
            wele = driver.findElement(By.xpath(objXpath));
            now = System.currentTimeMillis();
        }

        if (wele == null) {
            throw new Exception("Can not find out the element: " + objXpath);
        }

        return wele;
    }

    /**
     * 找元素，最长等待maxWait 秒
     *
     * @param xpath  String
     * @param driver RemoteWebDriver
     * @return List<WebElement>
     * @throws UINotFoundException
     */
    protected static List<WebElement> findObjectsByXPath(String xpath, WebDriver driver) throws UINotFoundException {
        return findObjectsByXPath(xpath, driver, maxWait);
    }

    /**
     * 找元素
     *
     * @param xpath   元素的xpath定位
     * @param driver  web driver
     * @param waitMax 最长等待秒数
     * @return List<WebElement> 元素列表
     * @throws UINotFoundException
     */
    protected static List<WebElement> findObjectsByXPath(String xpath, WebDriver driver, long waitMax) throws UINotFoundException {
        int size = 0;
        List<WebElement> objs = null;
        long start = System.currentTimeMillis();
        long now = System.currentTimeMillis();
        logger.info("Finding the element: " + xpath + " ...");
        while (((now - start) < waitMax * 1000) && (size == 0)) {
            Tools.wait(1);
            objs = driver.findElements(By.xpath(xpath));
            if (objs != null) {
                size = objs.size();
            }
            now = System.currentTimeMillis();
        }

        if (size == 0) {
            throw new UINotFoundException("Could not find the element which located by " + xpath);
        } else {
            logger.info("The element: " + xpath + " is founded.");
            return objs;
        }
    }
}
